/**
 * Created by singemazuo on 1/30/16.
 */

var express = require('express');
var router = express.Router();
var async = require('async');
var jwt = require('jwt-simple');
var moment = require('moment');

var auth = require('../models/authorizedModel');

function makeToken(auth){
    var expires = moment().add(7,'days').valueOf();
    var token = jwt.encode({
        iss: auth.photo,
        exp: expires
    }, 'shengyanhong1988');// 'shengyanhong-19880620&zuoyinbin-19860714'
    return token;
};

var jsonObj = function(status,content){
    var obj = {
        status:status,
        msg:'',
        content:content,
    };
    return obj;
};

var _auth = function(req){
    var _phone = req.query.phone;
    if (typeof _phone == "undefined"){
        _phone = req.body.phone;
    }

    var _password = req.query.password;
    if (typeof _password == "undefined"){
        _password = req.body.password;
    }

    return {phone:_phone,password:_password};
};

router.post('/signin', function (req,res) {
    var _ = _auth(req);
    auth.valid(_,function(err){
        if (err){
            // 需要注册
            res.json(jsonObj('401',''));
        }else{
            // 成功，返回token
            var obj = jsonObj('200',{token:makeToken(_)});
            res.json(obj);
        }
    });
});

router.post('/signup', function (req,res) {
    auth.valid(_auth(req),function(err){
        if (err){
            // 不存在就注册

            auth.add(_auth(req),function(err){
                if(err == null){
                    res.send('注册成功!');
                }else{
                    res.send('注册失败!');
                }
            });
        }else{
            // 存在就返回注册失败

            res.json(jsonObj('200',{content:'用户存在!'}));
        }
    });
});

module.exports = router;
